<template>
  <div @click="onCellClick" class="edit-cell">
    <!-- 非编辑模式 -->
    <el-tooltip v-if="!isEditing" content="点击编辑" placement="top">
      <div class="cell-content">
        <slot name="content">{{ value }}</slot>
      </div>
    </el-tooltip>
    
    <!-- 编辑模式 -->
    <component
      v-else
      :is="editableComponent"
      ref="inputRef"
      v-bind="$attrs"
      v-model="currentValue"
      @blur="onInputExit"
      @change="onInputExit"
    >
      <slot name="edit-component-slot"></slot>
    </component>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'

const props = defineProps({
  value: [String, Number, Date],
  canEdit: { type: Boolean, default: true },
  editableComponent: { type: String, default: 'el-input' }
})

const emit = defineEmits(['update:value', 'change'])
const isEditing = ref(false)
const currentValue = ref(props.value)
const inputRef = ref()

watch(() => props.value, (newVal) => {
  currentValue.value = newVal
})

const onCellClick = () => {
  if (props.canEdit && !isEditing.value) {
    isEditing.value = true
    nextTick(() => {
      inputRef.value?.focus?.()
    })
  }
}

const onInputExit = () => {
  if (isEditing.value) {
    isEditing.value = false
    emit('update:value', currentValue.value)
    emit('change', currentValue.value)
  }
}
</script>

<style scoped>
.edit-cell {
  min-height: 25px;
  cursor: pointer;
}
.cell-content {
  padding: 8px 0;
}
</style>